package cn.finder0519.networkspeedtest;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.*;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    Button testBtn;
    TextView resultText;

    private AlertDialog progressDialog;

    private void showProgressDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false); // 禁止点击外部取消
        builder.setView(R.layout.dialog_progress);
        progressDialog = builder.create();
        progressDialog.show();
    }

    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
        String resultStr = sharedPreferences.getString("result", "");
        testBtn = findViewById(R.id.testBtn);
        resultText = findViewById(R.id.resultText);

        if (resultStr.isEmpty()) {
            resultText.setText("No result");
        } else {
            resultText.setText(sharedPreferences.getString("result", "No result"));
        }

        testBtn.setOnClickListener(v -> new NetworkTestTask().execute());
    }

    class NetworkTestTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showProgressDialog();
            resultText.setText("Please wait...");

        }

        @Override
        protected String doInBackground(String... urls) {
            boolean internetReachable = NetworkUtils.isInternetReachable();
            if (!internetReachable) {
                return "Cannot connect to the server.";
            }
            StringBuilder result = new StringBuilder();

            // --- Ping 测试 ---
            try {
                String ipAddr = "speed.cloudflare.com";
                Process process = Runtime.getRuntime().exec("/system/bin/ping -c 4 " + ipAddr);
                InputStream input = process.getInputStream();
                int len;
                byte[] buffer = new byte[1024];
                while ((len = input.read(buffer)) != -1) {
                    result.append(new String(buffer, 0, len));
                }
                process.waitFor();
                input.close();
            } catch (Exception e) {
                result.append("Ping Error: ").append(e.getMessage()).append("\n");
            }

            // --- 下载速度测试（最多持续15秒） ---
            try {
                long startTime = System.currentTimeMillis();
                long maxDuration = 15_000; // 最长下载时间15秒

                URL testUrl = new URL("https://speed.cloudflare.com/__down?bytes=104857600");
                HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
                conn.setConnectTimeout(5000); // 连接超时：5秒
                conn.setReadTimeout(5000);    // 读取超时：5秒
                conn.setDoInput(true);
                conn.connect();

                int totalBytes = 0;
                byte[] buffer = new byte[1024];
                InputStream input = conn.getInputStream();
                int bytesRead;

                while ((bytesRead = input.read(buffer)) != -1) {
                    totalBytes += bytesRead;

                    // 超时判断
                    if (System.currentTimeMillis() - startTime > maxDuration) {
                        break;
                    }
                }

                input.close();
                conn.disconnect();

                long endTime = System.currentTimeMillis();
                double durationSec = (endTime - startTime) / 1000.0;

                // 避免除以0
                if (durationSec < 0.1) durationSec = 0.1;

                double speedMbps = (totalBytes * 8 / 1_000_000.0) / durationSec;

                double speedBytesPerSec = totalBytes / durationSec;

                String speedFormatted;
                if (speedBytesPerSec >= 1024 * 1024) {
                    // 大于1MB/s
                    double speedMBps = speedBytesPerSec / (1024 * 1024);
                    speedFormatted = String.format("%.2f MB/s", speedMBps);
                } else if (speedBytesPerSec >= 1024) {
                    // 大于1KB/s
                    double speedKBps = speedBytesPerSec / 1024;
                    speedFormatted = String.format("%.2f KB/s", speedKBps);
                } else {
                    // 小于1KB/s
                    speedFormatted = String.format("%.2f B/s", speedBytesPerSec);
                }


                result.append("\nDownload Speed: ")
                        .append(String.format("%.2f Mbps", speedMbps))
                        .append(" (")
                        .append(speedFormatted)
                        .append(")");
            } catch (Exception e) {
                result.append("\nDownload Speed Test Error: ").append(e.getMessage());
            }

            return result.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            dismissProgressDialog();
            resultText.setText(result);

            SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("result", result);
            editor.apply();
        }

    }
}